package com.fiberhome.app.network.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import io.reactivex.annotations.NonNull;

/**
 * tcp socket
 * Created by Deed on 2018/1/9.
 */

class TcpSender extends SocketSender {

    /**
     *
     */
    private Socket socket;

    /**
     *
     */
    private TcpBuilder tcpBuilder;

    /**
     *
     * @param tcpBuilder TcpBuilder
     */
    TcpSender(@NonNull TcpBuilder tcpBuilder) {
        super(tcpBuilder);
        this.tcpBuilder = tcpBuilder;
    }

    @Override
    protected String send() throws IOException {
        OutputStream os = null;
        InputStream is = null;
        String result = null;
        String sendData = tcpBuilder.sendData;
        try {
            socket = new Socket();
            socket.setSoTimeout(tcpBuilder.timeOut);
            InetAddress host = InetAddress.getByName(tcpBuilder.ipAddress);
            if (host != null) {
                socket.connect(new InetSocketAddress(host, tcpBuilder.port), tcpBuilder.timeOut);
                os = socket.getOutputStream();
                is = socket.getInputStream();
                if (tcpBuilder.tcpPacket == null) {
                    tcpBuilder.tcpPacket = new DefaultTcpPacket();
                }
                os.write(tcpBuilder.tcpPacket.sendBytes(sendData));
                os.flush();
                result = tcpBuilder.tcpPacket.getResult(is);
            } else {
                throw new IOException("Invalid host : " + tcpBuilder.ipAddress);
            }
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return result;
    }

    @Override
    public void cancel() {
        if (socket != null) {
            try {
                socket.close();
                socket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
